package net.kazed.nextaction.process;

import net.kazed.nextaction.R;
import net.kazed.nextaction.context.activity.StartedTasksActivity;
import net.kazed.nextaction.database.Task;
import net.kazed.nextaction.database.TaskStatus;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;

/**
 * Processes tasks with start date.
 * @author Koert Zeilstra
 *
 */
public class StartDateProcessor extends BroadcastReceiver {

    public static final int NOTIFICATION_ID = R.string.process_start_date_notification;

    @Override
    public void onReceive(Context context, Intent intent) {
        ContentValues values = new ContentValues();
        values.put(Task.Column.STATUS, TaskStatus.NEXT_ACTION.getType());
        int numberOfItems = context.getContentResolver().update(Task.CONTENT_URI, values,
                        Task.Column.START_DATE + " is not null and " + Task.Column.START_DATE + " < ? and "
                        + Task.Column.STATUS + " = " + TaskStatus.IDEA.getType(),
                        new String[] {Long.toString(System.currentTimeMillis())});
        if (numberOfItems > 0) {
            NotificationManager notificationManager = (NotificationManager) context.getSystemService(
                            Service.NOTIFICATION_SERVICE);
            Resources resources = context.getResources();
            Notification notification = new Notification(android.R.drawable.ic_menu_info_details,
                            resources.getString(R.string.process_start_date_notification), System.currentTimeMillis());
            Intent applicationIntent = new Intent(context, StartedTasksActivity.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, applicationIntent, 0);
            String text = null;
            if (numberOfItems == 1) {
                text = resources.getString(R.string.process_start_date_notification_text_1);
            } else {
                text = resources.getString(R.string.process_start_date_notification_text_m, numberOfItems);
            }
            notification.setLatestEventInfo(context, resources.getText(R.string.process_start_date_notification_title),
                            text, pendingIntent);
            notificationManager.notify(NOTIFICATION_ID, notification);
        }
        
    }

}
